from django.shortcuts import render, redirect, HttpResponse
from django import forms
from io import BytesIO
from app01.utils.bootstrapForm import BootstrapForm
from app01.utils.encrypt import md5
from app01.utils.code import check_code
from app01 import models


class AccountForm(BootstrapForm):
    username = forms.CharField(label='用户名')
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    img_text = forms.CharField(label='验证码')

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)


def img_code(request):
    """生成图片验证码"""
    code_img, text_img = check_code()
    stream = BytesIO()
    code_img.save(stream, 'png')
    request.session['text_img'] = text_img
    # 设置验证码60秒过期
    request.session.set_expiry(60)
    return HttpResponse(stream.getvalue())


def login(request):
    if request.method == 'GET':
        form = AccountForm()
        return render(request, 'login.html', {'form': form})
    form = AccountForm(data=request.POST)
    if form.is_valid():
        input_code = form.cleaned_data.pop('img_text')
        text_code = request.session.get('text_img')
        # 判断输入的验证码是否一致
        if input_code.upper() != text_code.upper():
            form.add_error('img_text', '验证码不一致！')
            return render(request, 'login.html', {'form': form})
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码不一致！")
            return render(request, 'login.html', {'form': form})
        request.session['info'] = {'id': admin_object.id, 'username': admin_object.username}
        # 设置7天免登录
        request.session.set_expiry(60*60*24*7)
        return redirect('/admin/list/')
    return render(request, 'login.html', {'form': form})


# 注销
def logout(request):
    request.session.clear()
    return redirect('/login/')
